package org.hq.service;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.hq.pojo.LoginUser;
import org.hq.pojo.WebUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.io.IOException;

/**
 * token 过滤
 */

public class TokenFlterService extends HttpFilter {
    public TokenFlterService(TokenService ts, AuthenticationManager am) {
        this.ts = ts;
        this.am = am;
    }

    private TokenService ts;
    private AuthenticationManager am;
    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //判断是否是访问登录 uri
       String uri= request.getRequestURI();
       if (uri.equals("/logintojson") || uri.equals("/login")) {
           //放行访问
           chain.doFilter(request, response);
           return;
       }

       // 1 获取 token
      String token= request.getHeader("token");
      if (token == null || token.equals("")) {
          return;
      }
      System.out.println(token);
   WebUser user= ts.isToken(token);
      if (user == null) {
          System.out.println("用户为空");
          return;
      }
        try {
            LoginUser loginUser = new LoginUser(user);
            // 封装登录系统用户
            Authentication authenticate  = new UsernamePasswordAuthenticationToken(loginUser, user.getPassword());
            //判断是否认证成功
            //将认证用户保存到上下文去
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            //放行访问
            chain.doFilter(request, response);
        } catch (Exception e) {

        }
    }
}
